<?php declare(strict_types=1);

$di = \application\units\Di::getInstance();

$params = [
    'admin_id'    => $di->auth->id,
    'id'          => $di->request->params('id'),
    'pid'         => $di->request->params('pid'),
    'status'      => $di->request->params('status'),
    'name'        => $di->request->params('name'),
    'resource_id' => (string)$di->request->params('resource_id'),
];

if ('' == $params['name']) throw new \LogicException('角色组名称不能为空');

if ($params['admin_id'] !== null) {
    // 不能操作不属于当前管理员的角色组
    $roleIds = $di->auth->getChildrenRoleIds($params['admin_id'], true);
    if (!in_array($params['pid'], $roleIds)) throw new \LogicException('不能操作不属于当前管理员的角色组');
}

// 不能将PID设置为当前角色组的下级ID
$roleIds = $di->auth->getChildrenRoleIdsByRoleId($params['id'], true);
if (in_array($params['pid'], $roleIds)) throw new \LogicException('上级角色组ID不能为当前角色组的下级ID');


$has = $di->db->find('select * from admin_role where name=:name and id<>:id', [
    'name' => $params['name'],
    'id'   => $params['id'],
]);

if ($has) throw new LogicException('角色名称已存在');

$row = $di->db->find('select * from admin_role where id=:id', [
    'id' => $params['id'],
]);

if (!$row) throw new \LogicException('未找到记录');

try {
    $di->db->beginTransaction();
    
    $stat = $di->db->execute('update admin_role set name=:name,pid=:pid,status=:status,update_time=:update_time where id=:id', [
        'id'          => $params['id'],
        'name'        => $params['name'],
        'pid'         => $params['pid'],
        'status'      => $params['status'],
        'update_time' => date('Y-m-d H:i:s'),
    ]);
    
    if ($stat->rowCount() <= 0) throw new \PDOException('操作失败');
    
    $hasResourceId = array_column($di->db->query('select resource_id from admin_role_resource_access where role_id=:role_id', [
        'role_id' => $params['id'],
    ]), 'resource_id');
    
    $params['resource_id'] = array_filter(explode(',', $params['resource_id']));
    
    $addResourceId = array_diff($params['resource_id'], $hasResourceId);
    $delResourceId = array_diff($hasResourceId, $params['resource_id']);
    
    if ($delResourceId) {
        $stat = $di->db->execute('delete from admin_role_resource_access where role_id=:role_id and resource_id in (:resource_id)', [
            'role_id'     => $params['id'],
            'resource_id' => $delResourceId,
        ]);
        if ($stat->rowCount() <= 0) throw new \PDOException('操作失败');
    }
    // 添加角色组
    foreach ($addResourceId as $resourceId) {
        
        if ($resourceId <= 0) throw new LogicException('权限ID不能小于等于0');
        
        $stat = $di->db->execute('insert into admin_role_resource_access(role_id, resource_id, update_time, create_time)
                          values (:role_id, :resource_id, :update_time, :create_time)', [
            'role_id'     => $params['id'],
            'resource_id' => $resourceId,
            'update_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
        ]);
        if ($stat->rowCount() <= 0) throw new \PDOException('操作失败');
    }
    $di->db->commit();
} catch (\Exception $e) {
    $di->db->rollback();
    throw $e;
}

return [];